//
//  PartSearchVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/29.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "PartSearchVC.h"
#import "AFNetworking.h"
#import "CustomPopOverView.h"
#import "Masonry.h"
#import "YYpartCell.h"
#import "PartDataModel.h"
#import "MslistModel.h"
#import "PartDetailVC.h"
#import "JoinFaluterView.h"
#import "ServerUnusualView.h"
#import "FallLineView.h"
#import "MBProgressHUD.h"
#import "NothingDataView.h"
#import "YYpartDataModel.h"
@interface PartSearchVC ()<UITableViewDelegate,UITableViewDataSource,CustomPopOverViewDelegate,JoinFalutDelegate,FallLineDelegate,ServerUnsualDelegate,NothingViewDelegate>
{
    UIButton *_fgstextTF;
    UITextField *_searchText;
    NSInteger gsId;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;

}
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *FGS_arry;//所有分公司
@property (nonatomic,strong)NSMutableArray *FGSid_arry;//所有分公司id;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation PartSearchVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self FGSload];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"配件搜索";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    _FGS_arry = [[NSMutableArray alloc]init];
    _FGSid_arry = [[NSMutableArray alloc]init];
    _dataSource = [[NSMutableArray alloc]init];
    
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.rowHeight = 70;
    _tableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [_tableview setTableFooterView:v];
    UIView *heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 90)];
    heardView.backgroundColor = [UIColor whiteColor];
    heardView.layer.shadowColor = [UIColor grayColor].CGColor;
    heardView.layer.shadowOffset = CGSizeMake(0, 2);
    heardView.layer.shadowOpacity = 1.0f;
    [_tableview setTableHeaderView:heardView];
    UILabel *leftT = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 60, 21)];
    leftT.text = @"分公司";
    leftT.textColor = UIColorFromRGB(0x4d4d4d);
    leftT.font = [UIFont systemFontOfSize:19.0];
    [heardView addSubview:leftT];
    _fgstextTF = [UIButton buttonWithType:UIButtonTypeSystem];
    [_fgstextTF setTitle:@"选择分公司" forState:UIControlStateNormal];
    [_fgstextTF setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
    _fgstextTF.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _fgstextTF.titleLabel.font = [UIFont systemFontOfSize:19.0];
    _fgstextTF.layer.cornerRadius = 5;
    //btn标题对齐方式
    _fgstextTF.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_fgstextTF addTarget:self action:@selector(chooseFgs:) forControlEvents:UIControlEventTouchUpInside];
    [heardView addSubview:_fgstextTF];
    [_fgstextTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(heardView).offset(10);
        make.left.equalTo(leftT.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-90, 30));
    }];
    
    _searchText = [[UITextField alloc]init];
    _searchText.placeholder = @"🔍输入编码/配件关键字";
    _searchText.borderStyle = UITextBorderStyleNone;
    _searchText.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _searchText.textColor = UIColorFromRGB(0x4d4d4d);
    _searchText.layer.cornerRadius = 5;
    [heardView addSubview:_searchText];
    [_searchText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_fgstextTF.mas_bottom).offset(10);
        make.left.equalTo(heardView).offset(20);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-90, 30));
    }];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    [btn setTitle:@"搜索" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [heardView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_fgstextTF.mas_bottom).offset(10);
        make.left.equalTo(_searchText.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];

    [self.view addSubview:_tableview];
    

}
- (void)FGSload{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_partFGS parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_FGS_arry removeAllObjects];
        [_FGSid_arry removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYpartDataModel *model = [[YYpartDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYbeanListModel *Bmodel in model.beanList) {
            [_FGS_arry addObject:Bmodel.branchName];
            [_FGSid_arry addObject:[NSString stringWithFormat:@"%ld",Bmodel.branchId]];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        //NSLog(@"gs%@,gsid%@",_FGS_arry,_FGSid_arry);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}
#pragma mark-->tableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YYpartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[YYpartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MslistModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MslistModel *model = _dataSource[indexPath.row];
    PartDetailVC *vc = [[PartDetailVC alloc]init];
    vc.logId = model.logId;
    vc.number = model.numb;
    vc.unit = model.unit;
    vc.discrib = model.discrib;
    vc.time = model.tm;
    vc.storeName = model.storeName;
    vc.storeCode = model.storeCode;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)searchBtnClick{
    
    [self SearchNetWorking];
}
- (void)SearchNetWorking{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"搜索中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_partSearch parameters:@{@"brId":[NSString stringWithFormat:@"%ld",gsId],@"mskeyword":_searchText.text} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_dataSource removeAllObjects];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        PartDataModel *model = [[PartDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (MslistModel *msModel in model.mslist) {
            [_dataSource addObject:msModel];
        }
        if (_dataSource.count == 0) {
            self.tableview.scrollEnabled = NO;
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 154, kSCREEN_WIDTH, kSCREEN_HEIGHT-154) title:@"没有搜索到您要的数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }else{
            self.tableview.scrollEnabled = YES;
            [_nothing removeFromSuperview];
        }
        
        [self.tableview reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
        
    }];

}
-(void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self SearchNetWorking];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self SearchNetWorking];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self SearchNetWorking];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self SearchNetWorking];
}
- (void)chooseFgs:(UIButton *)sender
{
    
    if (_FGS_arry.count == 0) {
        
    }else{
    CustomPopOverView *view = [[CustomPopOverView alloc]initWithBounds:CGRectMake(0, 0, kSCREEN_WIDTH-80, kSCREEN_HEIGHT/3) titleMenus:_FGS_arry];
    view.containerBackgroudColor = [UIColor clearColor];
    view.layer.shadowColor = [UIColor grayColor].CGColor;
    view.layer.shadowOpacity = 1.0f;
    view.layer.shadowOffset = CGSizeMake(0,0);
    view.delegate = self;
        [view showFrom:sender alignStyle:CPAlignStyleCenter];
    }
}
- (void)popOverView:(CustomPopOverView *)pView didClickMenuIndex:(NSInteger)index
{
    
    [_fgstextTF setTitle:_FGS_arry[index] forState:UIControlStateNormal];
    [_fgstextTF setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    gsId = [_FGSid_arry[index]integerValue];
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end
